package com.javaxiaobear.base.framework.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.math.BigDecimal;

public class BigDecimalSerializer extends StdSerializer<BigDecimal> {

  public static final BigDecimal LOW = BigDecimal.valueOf(-9007199254740991L);
  public static final BigDecimal HIGH = BigDecimal.valueOf(9007199254740991L);
  public static final BigDecimalSerializer instance = new BigDecimalSerializer();

  protected BigDecimalSerializer() {
    super(BigDecimal.class);
  }

  @Override
  public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider)
      throws IOException {
    if (value == null) {
      gen.writeNull();
    } else {
      int scale = value.scale();
      String outText;
      if (scale >= -100 && scale < 100) {
        outText = value.toPlainString();
      } else {
        outText = value.toString();
      }
      if (scale == 0
          && outText.length() >= 16
          && (value.compareTo(LOW) < 0 || value.compareTo(HIGH) > 0)) {
        gen.writeString(outText);
        return;
      }
      gen.writeNumber(outText);
    }
  }
}
